import { useEffect, useState } from 'react';
import moment from 'moment';
import {
  Radio,
  Form,
  Input,
  Select,
  message,
  Upload,
  Button
} from 'antd';

import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import Fromrate from '../../assets/scss/news/newsOperate.module.scss'
import Editor from '../../components/Editor'
import type { RadioChangeEvent } from 'antd';
import { Cationlist, NewsAdd, Newsget } from '../../apis/News/news'
import { CationDta, } from '../../apis/News/newstype';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import { useNavigate } from "react-router-dom";
import { useSearchParams } from "react-router-dom"



const NewsOperate = (): JSX.Element => {

  const [params] = useSearchParams()
  // 列表页面传递的值
  const id: any = params.get("id")

  const navigate = useNavigate()

  const [GetSucs, SetSucs]: any = useState({})

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  // 富文本子组件传递的值
  const [contentText, setContentText] = useState('')
  const content = (val: string) => {
    console.log(88888888, val);
    setContentText(val)
    SetSucs({ ...GetSucs, content: val })
  }

  // 图片上传自带方法
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  // 单选自带方法
  const [value, setValue] = useState(1);

  const ChangeRadio = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setValue(e.target.value);
  };


  // 公告分类参数
  const row: CationDta = {
    page: 1,
    psize: 3
  }

  // 公告分类数组
  const [Catilsit, CatilsitEit] = useState([])

  //  请求公告分类
  const GetNoticetypelist = async () => {
    const res: any = await Cationlist(row)
    console.log(res);
    if (res.errCode === 10000) {
      CatilsitEit(res.data.list)
      console.log(Catilsit);
    }
  }


  const [loginform] = Form.useForm();


  // 点击确定
  const Determine = async (values: any,) => {
    if (id) {
      console.log(values);

      values.id = id
      values.hits = 0
      values.edituser = sessionStorage.getItem('name')
      values.addtime = moment(new Date).format('YYYY-MM-DD HH:mm:ss')
      values.content = GetSucs.content
      // 不点击编辑图片  没有图片 
      if (values.picture === null && !GetSucs.picture) {
        values.picture = GetSucs.picture
      }

      // 点击编辑图片    并且上传图片不等于回显图片
      else if (values.picture && !GetSucs.picture) {
        values.picture = values.picture.file.response.data
      } else
        // 点击编辑图片   并且上传图片等于回显图片
        if (values.picture && values.picture == GetSucs.picture) {
          values.picture = GetSucs.picture
        } else

        // 没有图片点击编辑图片
        {
          values.picture = values.picture.file.response.data
        }

      const res: any = await NewsAdd(values)
      console.log(res);
      if (res.errCode === 10000) {
        navigate('/home/news')
        message.open({
          type: 'success',
          content: '编辑成功',
        });
      }
    } else {
      values.id = 0
      values.hits = 0
      values.edituser = sessionStorage.getItem('name')
      values.addtime = moment(new Date).format('YYYY-MM-DD HH:mm:ss')
      values.content = contentText
      if (values.picture) {
        values.picture = values.picture.file.response.data
      }
      const res: any = await NewsAdd(values)
      console.log(res);
      if (res.errCode === 10000) {
        navigate('/home/news')
        message.open({
          type: 'success',
          content: '添加成功',
        });
      }
    }
  };

  // 获取单条公告信息
  const GetonError = async () => {
    const res: any = await Newsget({ id: id })
    console.log(123, res);
    if (res.errCode === 10000) {
      SetSucs(res.data)
      setImageUrl('http://estate.eshareedu.cn/estate/upload/' + res.data.picture)
    }
  }


  useEffect(() => {
    // 请求公告分类
    GetNoticetypelist()

    // 获取单条公告信息
    GetonError()
  }, [])


  useEffect(() => {
    if (id) {
      loginform.setFieldsValue({
        title: GetSucs.title,
        state: GetSucs.state,
        type: GetSucs.type,
        picture: GetSucs.picture,
        content: GetSucs.content,
      })
    }
  }, [GetSucs])

  return (
    <div>
      <div className={Fromrate.title}>公告管理</div>
      <Form className={Fromrate.NewsFrom} form={loginform} onFinish={Determine}>
        <Form.Item label="标题" className={Fromrate.NewsFitle} name='title' rules={[{ required: true, message: '标题不能为空!' }]}>
          <Input placeholder='标题名称' />
        </Form.Item>

        <Form.Item className={Fromrate.NewsEditor} name='content'>
          <Editor txt={GetSucs.content} getcontent={content}></Editor>
        </Form.Item>


        <Form.Item label="公告图片" className={Fromrate.Newsimg} name='picture' rules={[{ required: true, message: '公告图片不能为空!' }]}>
          <Upload
            name="file"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            headers={{ Authorization: sessionStorage.getItem('token') || '' }}
            action="http://estate.eshareedu.cn/estate/api/upload/add"
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {
              imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton
            }
          </Upload>
        </Form.Item>

        <Form.Item label="状态" name='state' className={Fromrate.Radio} rules={[{ required: true, message: '状态不能为空!' }]}>
          <Radio.Group onChange={ChangeRadio} value={value}>
            <Radio value={1}>开启</Radio>
            <Radio value={0}>关闭</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item label="公告类型" name='type' className={Fromrate.Select} rules={[{ required: true, message: '公告类型不能为空!' }]}>
          <Select placeholder="请选择" >
            {
              Catilsit.map((item: any) => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              )
              )
            }
          </Select>
        </Form.Item>

        <Form.Item className={Fromrate.Button}>
          <Button type="primary" htmlType="submit" className={Fromrate.Button1}>确定</Button>
          <Button className={Fromrate.Button2}>取消</Button>
        </Form.Item>
      </Form>
    </div>
  )
}
export default NewsOperate;